<?php

namespace Bean\Flow;

abstract class PostsFlow extends \Bean\Flow\GenericFlow {

	private $_data;
	private $_posts = array();
	
	public function __construct( $data ) {
		parent::__construct();
		$this->_data = $data;
	}

	public static function getFlow( $flow ) {
		$class = get_class() . '\\' . $flow['type'] . 'Flow';
		$instance = new $class( $flow );
		return $instance;
	}
	
	public static function get( $flow_id ) {
		$flow = _q()->get1( 'posts_flows', array( 'flow_id' => $flow_id ) );
		return self::getFlow( $flow );
	}
	
	public function getFlowId() {
		return $this->_data['flow_id'];
	}
	
	public function getPosts( $i = 0 ) {

		if( !isset($this->_posts[$i]) ) {
			$start = (int) $i*self::N_ITEMS_BY_BLOCK;
			$size = self::N_ITEMS_BY_BLOCK;
			$results = _q()->getE( 
				'posts', 
				array( 'flow_id' => $this->getFlowId() ), 
				'publication_time desc', $start, $size );

			$posts = array();
			foreach( $results as $post ) {
				$posts[] = \Bean\Flow\PostsFlow\Item::getItem( $post, $this );
			}
			$this->_posts[$i] = $posts;
		}
		return $this->_posts[$i];
	}
	
	public function getItems( $i = 0 ) {
		return $this->getPosts( $i );
	}
	
	public function addItem( $data ) {
		$data['type'] = 'User';
		return $this->addPost( $data );
	}
	
	public function addPost( $data ) {
		$now = _now();
		$post_id = _q()->set1( 'posts',
			array(
				'user_id' => _u()->getUserId(),
				'flow_id' => $this->getFlowId(),
				'type' => $data['type'],
				'message' => $data['message'],
				'publication_time' => $now
			) );

		return \Bean\Flow\PostsFlow\Item::getItem( array( 
			'flow_id' => $this->getFlowId(),
			'post_id' => $post_id,
			'message' => $data['message'],
			'type' => $data['type'],
			'publication_time' => $now,
			'user_id' => _u()->getUserId()
		), $this );
	}
}
